<template>
	<view class="container">
		<plublic-navbar :is-back="true" :title="title" :leftIconColor="'#ffffff'" :background="background"></plublic-navbar>
		<!-- <view class="borderbox">
			
		</view> -->
		<view class="vertical-scan-animation u-flex u-row-center">
			<u--image :src="`${imgUrl}sm.png`" width="650rpx" height="80rpx" mode="heightFix"></u--image>
		</view>
        <camera device-position="back" flash="off" @error="error" style="width: 100%; height:calc(100% - 220rpx);"></camera>
		<view class="footer">
			<view class="button" @click="takePhoto">
				<view class="box">
					<u--image :src="`${imgUrl}pbut.svg`" width="120rpx" height="120rpx" mode="heightFix"></u--image>
				</view>
			</view>
		</view>
        <u-popup :show="loading" mode="center" :safeAreaInsetBottom="false" round="10">
                    <view style="padding: 20rpx 40rpx;">
                       <u-loading-icon color="#25D59F" textColor="#25D59F" vertical="true" text="检测中" size="48" textSize="12" ></u-loading-icon>
                    </view>
        </u-popup>
        <u-modal :show="tips" :title="tipstitle" :showCancelButton="true" @close="tips = false" @cancel="tips = false" :closeOnClickOverlay="true" @confirm="confirm" confirmText="去添加" :content='tipscontent'></u-modal>
        	
        <!-- <view>预览</view> -->
        <!-- <image mode="widthFix" :src="src"></image> -->
    </view>
</template>

<script>

import { picturesIdentifyFood } from '../../common/api.js';
export default {
    data() {
        return {
			baseUrl: uni.$u.http.config.baseURL,
			imgUrl:uni.$u.http.config.imgURl,
			background: 'transparent',
			title: '识图',
            src:"",
			loading:false,
			tips:false,
			tipstitle:"检索提示",
			tipscontent:"已为你找到对应的物品，是否去添加饮食？",
			foodName:''
        }
    },
	onLoad() {
		this.requestCameraPermission()
	},
    methods: {
        async takePhoto() {
			console.log("检索提示")
            const ctx = uni.createCameraContext();
			console.log("检索提示",ctx)
            ctx.takePhoto({
                quality: 'high',
                success: (res) => {
					this.loading = true
                    this.src = res.tempImagePath
					if(this.src){
						this.uploadImg(res.tempImagePath)
					}
				
                }
            });
		
        },
		async uploadImg(src){
			const result = await this.uploadFilePromise(src);
			// console.log(result,"????????????????")
			if(JSON.parse(result).data){
				
				this.getphotoDetail(JSON.parse(result).data)
			}
		},
		
        error(e) {
            console.log(e.detail);
        },
		goPage(e){
			if(this.isLogin(e)){
				this.globals.linkJump({
				  url:e,
				  callback: () => {
				    uni.setStorageSync('pagelist',e)
				  }
				});
				// uni.navigateTo({
				// 	url: e
				// })
			}
		
		},
		async getphotoDetail(picUrl){
			let data = {
				picUrl: picUrl
			}
			
			await picturesIdentifyFood({
				params: data
			}).then(res => {
				this.loading = false
				if(!res.foodEnergyList){
					uni.$u.toast('暂未查找到相应数据');
					// this.$u.toast("暂未查找到相应数据");	
				}else{
					this.tips = true
					uni.setStorageSync('foodEnergyList',JSON.stringify(res.foodEnergyList))
					this.foodName = res.foodName
					// uni.$u.sleep(2000).then(() => {
					// 	this.goPage('/pages/service/list?foodname='+res.foodName)
					// })
				}
		
			}).catch(err => {
						
			})
		},
		confirm(){
			this.goPage('/pages/service/list?foodname='+this.foodName)
		},
		// 检查并请求授权摄像头权限
		requestCameraPermission() {
		  wx.getSetting({
		    success(res) {
		      if (!res.authSetting['scope.camera']) {
		        wx.authorize({
		          scope: 'scope.camera',
		          success() {
		            // 用户已经同意开启摄像头权限
		            console.log('获取摄像头权限成功');
		            // 接下来可以调用摄像头相关的API了
		          },
		          fail() {
		            // 用户拒绝授权，可以引导用户去设置中打开权限
		            wx.showModal({
		              title: '授权失败',
		              content: '需要从设置中开启摄像头权限',
		              showCancel: false,
		              confirmText: '去设置',
		              success: function(res) {
		                if (res.confirm) {
		                  wx.openSetting({
		                    success(res) {
		                      console.log(res.authSetting)
		                    }
		                  })
		                }
		              }
		            })
		          }
		        })
		      } else {
		        // 用户已授权，直接调用摄像头API
		        console.log('已获取摄像头权限');
		        // 调用摄像头相关API的代码...
		      }
		    }
		  })
		},
		uploadFilePromise(url) {
			let that = this
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: that.baseUrl+'app-api/infra/file/upload', 
					filePath: url,
					name: 'file',
					header: {
						Authorization: that.vuex_token || ''
					},
					formData: {
						user: 'test'
					},
					success: (res) => {
						setTimeout(() => {
							resolve(res.data)
						}, 1000)
					}
				});
			})
		},
    }
}
</script>

<style lang="scss">
page{
	width: 100%;
	height: 100%;
}
.container{
	width: 100%;
	height: 100%;
}
@keyframes scanTopToBottom {
  from {
    // transform: translateY(-100%);
	top:100rpx
  }
  to {
    // transform: translateY(100%);
	top:80vh
  }
}
.vertical-scan-animation {
	text-align: center;
	position: absolute;
	left: 0;
	z-index: 99;
  width: 100%; /* 定义动画的厚度 */
  height: 50rpx; /* 确保元素高度足够 */
  // background:#ffffff;
  // background: linear-gradient(to bottom, red, yellow, green, blue, indigo, violet); /* 颜色渐变 */
  animation: scanTopToBottom 3s infinite linear; /* 应用动画 */
}
.footer{
	position: fixed;
	bottom: 0;
	left: 0;
	z-index: 9;
	width: 100%;
	height: 220rpx;
	background: #ffffff;
	padding: 30rpx;
	.button{
		width: 120rpx;
		height: 120rpx;
		// border-radius: 60rpx;
		// background: #25D59F;
		margin: 0 auto;
		// padding: 2rpx;
		// .box{
		// 	width: 114rpx;
		// 	height: 114rpx;
		// 	border-radius: 60rpx;
		// 	background: #25D59F;
		// 	margin: 0 auto;
		// 	border: #ffffff 4rpx solid;
		// }
	}
	
}
</style>
